<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button
              size="small"
              type="primary"
              @click="addRuleFn"
            >新增角色</el-button>
            <!-- 表格 -->
            <el-table
              :data="tableData"
              border
              style="width: 100%"
              header-align="center"
            >
              <el-table-column
                label="序号"
                type="index"
                width="100px"
                align="center"
              />
              <el-table-column prop="name" label="角色" width="180" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作" width="260">
                <!-- 利用插槽实现自定义表格内容-->
                <!-- 利用插槽实现自定义表格的内容，这个是饿了么自带有的，row属性是指点击到的这一行，这样才知道删除那一行，根据他的id -->
                <template v-slot="{ row }">
                  <el-button
                    size="small"
                    type="success"
                    @click="assignPerm(row.id)"
                  >分配权限</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="editFn(row.id)"
                  >编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="delFn(row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- layout  prev,左，pager，中间的页码，next，右边，page-size，每页展示的数量-->
              <el-pagination
                layout="prev, pager, next"
                :total="total"
                :page-size="pagesize"
                @current-change="currentChange"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-form label-width="120px" disabled>
              <el-form-item label="公司名称">
                <el-input v-model="CompanyInfo.name" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="CompanyInfo.companyAddress" />
              </el-form-item>
              <el-form-item label="公司邮箱">
                <el-input v-model="CompanyInfo.mailbox" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="CompanyInfo.remarks" type="textarea" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增弹窗开始 -->
      <el-dialog
        :title="formData.id ? '编辑' : '新增'"
        :visible="showDialog"
        @close="closeFn"
      >
        <el-form
          ref="form"
          label-width="120px"
          :rules="rules"
          :model="formData"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="formData.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="formData.description" />
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-row type="flex" justify="center">
            <el-button size="small" @click="closeFn">取消</el-button>
            <el-button
              size="small"
              type="primary"
              @click="confirmFn"
            >确定</el-button>
          </el-row>
        </span>
      </el-dialog>
      <!-- 新增弹窗结束 -->
      <!-- 分配权限开始 -->
      <el-dialog
        title="分配权限"
        :visible="visibleDialog"
        @close="secondcloseFn"
      >
        <el-tree
          ref="tree"
          node-key="id"
          :data="treeData"
          :props="{ label: 'name' }"
          :check-strictly="true"
          show-checkbox
        />
        <span slot="footer" />
        <el-row type="flex" justify="center">
          <el-button size="small" type="primary" @click="okbtn">确定</el-button>
          <el-button size="small" @click="secondcloseFn">取消</el-button>
        </el-row>
      </el-dialog>
      <!-- 分配权限结束 -->
    </div>
  </div>
</template>

<script>
import {
  getRoleList,
  addRole,
  delRole,
  editRole, // 就是老师的getRoleById(id)
  updateRole,
  getCompanyInfo,
  assignPerm
} from '../../api/setting'
import { getPermissionList } from '../../api/permission'
import { listtotree } from '../../utils/index'
export default {
  data() {
    return {
      roleId: '',
      roleDetail: {}, // 用来存放角色详情
      visibleDialog: false, // 分配权限的控制闭合
      treeData: [], // 分配权限的数据存储
      tableData: [],
      total: 0,
      pagesize: 8,
      page: 1, // 默认请求第一页
      showDialog: false,
      formData: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名字不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '长度为2-10', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      CompanyInfo: {}
    }
  },
  async created() {
    // 渲染权限
    const res = await getPermissionList()
    console.log('res: ', res)
    this.treeData = listtotree(res, '0')
    //
    this.getRoleList()
    // const id = this.$store.state.user.userInfo.companyId
    const id = this.$store.state.user.userInfo.companyId
    console.log('id: ', id)

    this.CompanyInfo = await getCompanyInfo(id)
    console.log('this.CompanyInfo: ', this.CompanyInfo)
  },
  methods: {
    // 编辑权限
    async  okbtn() {
      // 获取到当前用户选择的权限合计
      const permIds = this.$refs.tree.getCheckedKeys()
      console.log('permIds: ', permIds)
      await assignPerm({
        id: this.roleId,
        permIds
      })
      this.secondcloseFn()
    },
    // 分配权限
    async assignPerm(id) {
      this.roleId = id// 把点击分配权限得到的ID存起来给后面的编辑功能使用
      this.visibleDialog = true
      this.roleDetail = await editRole(id)
      // 通过 keys 设置目前勾选的节点，使用此方法必须设置 node-key 属性
      // 设置 node-key 属性	(keys, leafOnly) 接收两个参数，1. 勾选节点的 key 的数组
      // . boolean 类型的参数，若为 true 则仅设置叶子节点的选中状态，默认值为 false
      // this.roleDetail.permIds 跟node-key="id"关联，如果第二个参数里面是name，那么node-key="name"
      this.$nextTick(() => { this.$refs.tree.setCheckedKeys(this.roleDetail.permIds) })// 写nextTick保证树形结构渲染成功后再来设置我们这个回显
    },
    async editFn(id) {
      this.showDialog = true
      this.formData = await editRole(id)
    },
    delFn(id) {
      this.$confirm('你确定删除吗', '提示', {
        type: 'warning'
      })
        .then(async() => {
          // 调用接口如果api那里需要参数的话，调佣的时候记得传
          await delRole(id)
          //
          if (
            this.tableData.length === 1 &&
            this.page !== 1 &&
            Math.ceil(this.total / this.pagesize) === this.page
          ) {
            this.page--
          }
          this.getRoleList()
          // console.log('id: ', id)
        })
        .catch(() => {
          console.log('你点击了删除')
        })
    },
    async confirmFn() {
      // 表单校验，给form设置res
      await this.$refs.form.validate()
      // 调用接口
      if (this.formData.id) {
        await updateRole(this.formData)
      } else {
        await addRole(this.formData)
      }

      // 关闭弹窗
      this.closeFn()
      // 刷新列表
      this.getRoleList()
    },
    closeFn() {
      // 重置表单
      this.formData = {
        name: '',
        description: ''
      }
      // 取消校验
      this.$refs.form.validateField()
      // 关闭弹窗
      this.showDialog = false
    },
    // 分配权限的关闭
    secondcloseFn() {
      // 重置表单
      // this.formData = {
      //   name: '',
      //   description: ''
      // }
      // 取消校验
      // this.$refs.form.validateField()
      // 关闭弹窗
      this.visibleDialog = false
    },

    addRuleFn() {
      this.showDialog = true
    },
    // 分页事件
    currentChange(currentpage) {
      this.page = currentpage
      this.getRoleList()
    },
    // 渲染列表
    async getRoleList() {
      const res = await getRoleList({
        page: this.page,
        pagesize: this.pagesize
      })
      console.log('res: ', res)
      this.total = res.total
      this.tableData = res.rows
    }
  }
}
</script>

<style lang="scss" scoped>
.el-button {
  margin-bottom: 20px;
}
</style>
